import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import Login from "@/views/index/Login";
import Store from "@/store";
import api from '@/utils/api';
//导入页面顶部加载进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//取消页面刷新时的圆圈
NProgress.configure({ showSpinner: false });

import { initMenu } from "@/utils/menuUtil";
import tokenUtil from "@/utils/tokenUtil";

//静态路由
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/',
    name: 'Frame',
    component: () => import('@/views/home/frame/Frame'),
    //redirect: '/home',
    children: [
      {
        path: 'home', //子路由的path不要以'/'开头
        name: 'Home',
        component: () => import('@/views/home/Home'),
      },
      {
        path: '/personalCenter',
        name: '个人中心',
        component: () => import('@/views/home/PersonalCenter'),
      },
    ]
  },
  /*{
    path: '/404',
    name: '404',
    visible: true,
    meta: {title: '404', cache: false},
    component: () => import('@/views/errorPage/404.vue'),
  },*/

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  //哈希模式
  // history: createWebHashHistory(),
  routes
})

/**
 * 路由导航 防止未登录就可以跳至主页面
 * to：将要去哪个页面
 * from：从那个页面过来
 * next：放行到哪个页面
 */
router.beforeEach((to, from, next) => {
  NProgress.start();
  //判断用户是否登录
  if(tokenUtil.getToken()){
    //获取vuex中存在用户登录信息
    //let userInfo = Store.state.userInfo;
    api.getRequest('/sysUser/getLoginUser').then(res => {
      if(res.success){
        let userInfo = res.data;
        if(userInfo && userInfo.id){
          //console.log(userInfo);
          //更新用户信息
          Store.commit('setUserInfo', userInfo);
          //获取菜单信息(工具类中的方法)
          initMenu(router, Store);

          //已经登录，便不可跳至登录页面
          if(to.path === '/login'){
            next('/');
          }else{
            if(to.meta.title){
              document.title = to.meta.title;
            }
            //解决在地址栏直接输入地址页面展示空白的bug
            console.log(to);
            //next();
            if (to.matched.length === 0) {
              next(to.path);
            }else{
              next();
            }
          }
        }else{
          console.log('登录已过期，请重新登录！');
        }
      }else{
        console.log('服务器异常，用户信息获取失败！');
      }
    })
  } else {
    //未登录（sessionStorage此时为空）,跳至登录页面
    if(to.path === '/login'){
      next();
    } else if(to.path === '/'){
      next('/login');
    } else if(to.path.startsWith('/index')){
      next('/login');
    } else {
      next(`/login?redirect=${to.fullPath}`);
    }
  }
})

router.afterEach(() => {
  NProgress.done();
})

export default router
